package com.testmanager.testmananger.shuiyou.strCompare.service;

import com.alibaba.fastjson.JSONObject;
import com.testmanager.testmananger.foundation.util.FlakeIdGenerator;
import com.testmanager.testmananger.shuiyou.common.util.ExcelOperte;
import com.testmanager.testmananger.shuiyou.strCompare.domain.*;
import com.testmanager.testmananger.shuiyou.strCompare.dto.CompareScriptDto;
import com.testmanager.testmananger.shuiyou.strCompare.mapper.CompareScriptMappre;
import com.testmanager.testmananger.shuiyou.strCompare.respository.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExportExcelService {

    @Autowired
    SyCompareDetailResultRepository  detailResultRepository;
    @Autowired
    SyCompareResultRepository  resultRepository;
    @Autowired
    SyCompareScriptKeyRepository  scriptKeyRepository;
    @Autowired
    SyCompareTaskRepository taskRepository;
    @Autowired
    SyDbManagerRepository dbManagerRepository;
    @Autowired
    SySqlCompareRepository scriptRepository;
    @Autowired
    SyTaskVariableValueRepository taskVariableValueRepository;
    @Autowired
    SqlCompareScriptService scriptService;

    @Autowired
    FlakeIdGenerator flakeIdGenerator;
    ExcelOperte excelOperte = new ExcelOperte();

   public void downloadAll(HttpServletResponse response) throws Exception {
       List<SyCompareScriptKeyEntity> scriptkeies = scriptKeyRepository.findAll();
       List<SySqlCompareScriptEntity> scriptEntities = scriptRepository.findAll();
       List<SyDbManagerEntity> dbs = dbManagerRepository.findAll();
       List<SyCompareTaskEntity> tasks = taskRepository.findAll();
       List<SyTaskVariableValueEntity> taskvariables = taskVariableValueRepository.findAll();

       HSSFWorkbook workbook = new HSSFWorkbook();
       workbook = excelOperte.createSheet(workbook,scriptEntities,"script");
        workbook = excelOperte.createSheet(workbook,scriptkeies,"scriptkey");
        workbook = excelOperte.createSheet(workbook,dbs,"db");
        workbook = excelOperte.createSheet(workbook,tasks,"task");
        workbook = excelOperte.createSheet(workbook,taskvariables,"taskvari");

       response.setContentType("application/octet-stream");
       response.setHeader("Content-disposition", "attachment;filename=" + "scriptinfo.xls");
//
//       rep.setHeader("Content-Disposition",  String.format("attachment; fileName=\"%s\"", URLEncoder.encode(fileName, "UTF-8")));
//
//       rep.setHeader("fileName",file.getName())   ;
       response.flushBuffer();
       workbook.write(response.getOutputStream());

       // response.getOutputStream().flush();
        workbook.close();
   }


   public void downloadScript(HttpServletResponse response ,List<CompareScriptDto> scriptDtos) throws Exception {
       List<SyCompareScriptKeyEntity> scriptKeyEntities = new ArrayList<>();
       List<SySqlCompareScriptEntity> scripts = scriptDtos.stream().map(t -> {
           List<SyCompareScriptKeyEntity> authors = t.getAuthors();
           List<SyCompareScriptKeyEntity> variables = t.getVariables();
           scriptKeyEntities.addAll(authors);
           scriptKeyEntities.addAll(variables);
           return CompareScriptMappre.toSqlCompareScriptEntity(t);
       }).collect(Collectors.toList());
       HSSFWorkbook workbook = new HSSFWorkbook();
       workbook = excelOperte.createSheet(workbook,scriptKeyEntities,"scriptkey");
       workbook = excelOperte.createSheet(workbook,scripts,"script");
       response.setContentType("application/octet-stream");
       response.setHeader("Content-disposition", "attachment;filename=" + "scriptinfo.xls");
       response.flushBuffer();
       workbook.write(response.getOutputStream());

       // response.getOutputStream().flush();
       workbook.close();

   }

    /**
     * 用例导出
     * @param projectid
     * @param scriptDtos
     * @return
     */
   public ResponseEntity uploadScript(long projectid,List<CompareScriptDto> scriptDtos){
       log.info(",uploadscript  ,scriptdto:{},projectid:{}",scriptDtos,projectid);
       scriptDtos.stream().parallel().forEach(t->{
           SySqlCompareScriptEntity script = scriptRepository.findByScriptno(t.getScriptno());
           if (null != script){
               script.setSrcSql(t.getSrcSql())
                       .setDestSql(t.getDestSql())
                       .setComment(t.getComment());
               scriptRepository.save(script);

           }else{
               t.setProjectid(projectid)
               .setId(flakeIdGenerator.newId());
               scriptService.saveOrUpdate(t);
           }


       });

       return  ResponseEntity.ok("success");


   }





//   public ResponseEntity uploadScript(MultipartFile file) throws IOException {
//       log.info("uploadScript");
//       HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
//       workbook.getSheet("script");
//       workbook.getSheet("scriptkey");
//
//
//   }


    /**
     * 结果导出
     * @param taskEntities
     * @return
     * @throws Exception
     */
   public void downloadResult(HttpServletResponse response,List<SyCompareTaskEntity> taskEntities) throws  Exception{
       HSSFWorkbook workbook = new HSSFWorkbook();



       for (SyCompareTaskEntity t : taskEntities){
           log.info("{}",taskEntities);
           SyCompareResultEntity resultEntity = resultRepository.findNearestResultBytaskid(t.getId());
           if (resultEntity == null){
               continue;
           }
           log.info("resultEntity:{}",resultEntity);
           List<SyCompareDetailResultEntity> detailResults = detailResultRepository.findAllByResultId(resultEntity.getId());
           String sheetname = "任务名,"+t.getName() +",失败数,"+resultEntity.getDiffCount();
          workbook =  excelOperte.createSheet(workbook,detailResults,sheetname);
       }





//       File file = new File("test1.xls");
//       OutputStream os = new BufferedOutputStream(new FileOutputStream(file));

       response.setContentType("application/octet-stream");
       //默认Excel名称
       response.setHeader("Content-Disposition", "attachment;fileName="+"result.xls");
       response.flushBuffer();
       workbook.write(response.getOutputStream());
       workbook.close();
//       os.flush();
//
//
//       HttpHeaders headers = new HttpHeaders();
//       headers.add("Content-Disposition", String.format("attachment;filename=\"%s", "result.xls"));
//       headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
//       headers.add("Pragma", "no-cache");
//       headers.add("Expires", "0");
//       ResponseEntity<Object> responseEntity = ResponseEntity.ok()
//               .headers(headers)
//               .contentLength(file.length())
//               .contentType(MediaType.parseMediaType("application/octet-stream"))
//               .body(new InputStreamResource(new FileInputStream(file)));







   // return  ResponseEntity.ok("success");





   }










}
